package cn.yj.core.kwfilter;

import cn.yj.common.AppExecutor;
import cn.yj.common.Enums;
import cn.yj.common.config.BeanTool;
import cn.yj.commons.utils.MapUtils;
import cn.yj.commons.utils.StringUtils;
import cn.yj.core.business.service.CustomerService;
import cn.yj.core.event.EventSource;
import cn.yj.core.event.KeyWorkFilterEvent;
import cn.yj.tools.exception.ServiceException;
import cn.yj.wechat.miniprogram.IWxMinilService;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * 敏感词过滤
 *
 * @author 永健
 * @since 2021-10-16 22:15
 */
@Component
public class KeyWorkFilterService implements ApplicationEventPublisherAware {

    private static ApplicationEventPublisher APP;

    /**
     * @param content 字数不能超过2500
     * @param openId  不能
     */
    public static Set<String> filter_search_out_word(String content, String openId) {
        Set<String> filterWord = new HashSet<>();
        if (StringUtils.isBlank(content)) {
            return filterWord;
        }

        String userCode = BeanTool.getBean(CustomerService.class).getUserCodeByOpenId(openId);

        if (StringUtils.isBlank(openId)) {
            throw new ServiceException("openId不为空");
        }

        if (content.length() > 250) {
            return new WordFilter().filter_search_out_word(content);
        }

        try {
            Map<String, Object> map = BeanTool.getBean(IWxMinilService.class).msgSecCheck(content, openId);
            if (!MapUtils.getIntVal(map, "code").equals(Enums.Common.ZERO)) {
                filterWord.add(MapUtils.getStringVal(map, "errmsg"));
                return filterWord;
            }
            filterWord = new WordFilter().filter_search_out_word(content);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Set<String> finalFilterWord = filterWord;
        AppExecutor.exec(() -> APP.publishEvent(new KeyWorkFilterEvent(new EventSource(content, finalFilterWord, userCode))));
        return filterWord;
    }

    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        APP = applicationEventPublisher;
    }
}
